using GLib;
using Gst;
using Rob;

namespace Rob
{
	namespace Actions
	{
		public class AnswerCall: Rob.Actions.Action
		{
			private string _record_file;
			private string dialer_interface;
			private string dialer_path;
			private string dialer_name;
			private Gst.Pipeline player;
			private Gst.Pipeline recorder;


			public bool load(string name, KeyFile kf)
			{
				try
				{

					_record_file = kf.get_string(name, "record_file");
					_name = name;
					_title = kf.get_string(name, "title");

				}
				catch ( GLib.KeyFileError e)
				{
					GLib.critical("Could not load %s: %s\n",name, e.message );
					return false;
				}
				return true;
			}
			public string record_file
			{
				get{return this.record_file;}
				set{this._record_file = value;}
			}
			public bool save(ref KeyFile kf)
			{
				try
				{
					base.save(ref kf);
					kf.set_string(name,"record_file",_record_file);
					kf.set_string(name,"title",title);
				}
				catch ( GLib.KeyFileError e )
				{
					GLib.critical("Could not save %s: %s\n", name,e.message);
					return false;
				}
				return true;
			}
			construct 
			{
				Time t = GLib.Time();
				_type = "answercall";
				_title = "Answer Call";
				_name = _type + "_" + t.to_string();
				_record_file = GLib.Environment.get_home_dir() + ".rob/messages/" + _name + ".ogg";

				//base();
			}
			private void run()
			{
				
			}
			private void incoming_call()
			{
				string nr;
				string date;
			
				TimeVal tv;
				tv.get_current_time();
				GLib.Date d ;//= new GLib.Date();
				d.set_time_val(tv);
				date = "%0i%0i%i".printf(d.get_month() , d.get_day(), d.get_year());

				string recdest = nr + "_" + date + ".wav";

				this.player = new Gst.Pipeline("player");
				this.recorder = new Gst.Pipeline("recorder");
				Gst.Element src = Gst.ElementFactory.make("filesrc", "playsource");
				src.set("location", _record_file );
				Gst.Element decoder = Gst.ElementFactory.make( "wavdec", "decoder");
				Gst.Element sink = Gst.ElementFactory.make( "alsasink", "sink" );
				sink.set("device", "Mono Playback Volume" );
				this.player.add_many( src, decoder, sink  );
				this.player.link_many(src, decoder, sink );
				//this.player.link_pads( "playsource", sink , "playsink");
				
				Gst.Element recsrc = Gst.ElementFactory.make("alsasrc", "recsrc");
				recsrc.set( "device", "Rx Mixer" );
				Gst.Element encoder = Gst.ElementFactory.make("wavenc", "encoder");
				Gst.Element filesink = Gst.ElementFactory.make("filesink", "dest");

				filesink.set("location", recdest );
				this.recorder.add_many( recsrc, encoder, filesink );
			}

			private void record()
			{
				
			}

			[ModuleInit]
			public Type register_rb_plugin (TypeModule module) 
			{
				stdout.printf ("Registering plugin %s\n", "AnswerCall");
				Gst.init( ref Rob.args );
				return typeof (Rob.Actions.AnswerCall);
			}
		}
	}
}
